package com.chainyoung.common.base;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.chainyoung.common.R;
import com.chainyoung.common.custom_widget.EmptyCallback;
import com.chainyoung.common.custom_widget.LoadingCallback;
import com.chainyoung.common.custom_widget.RetryCallback;
import com.chainyoung.common.common_widget.loadsir.callback.Callback;
import com.chainyoung.common.common_widget.loadsir.core.LoadService;
import com.chainyoung.common.common_widget.loadsir.core.LoadSir;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.mvp.IView;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.common.utils.Utils;
import com.chainyoung.common.view.ProcessDialog;
import com.chainyoung.common.view.kprogresshud.KProgressHUD;
import com.gyf.barlibrary.ImmersionBar;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.chainyoung.common.constant.LibConstant.IS_CUSTOME_SIZE;

public abstract class SimpleActivity extends AppCompatActivity implements IView {

    protected Unbinder mUnBinder;
    protected Activity mContext;

    protected LoadService mLoadService;
    public ProcessDialog mProcessDialog;

    protected AppComponent mAppComponent;

    public KProgressHUD hud;

    protected int sTheme;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (null != savedInstanceState) {
            savedInstanceState = null;
        }
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        if (!setFullScreen() && useDefaultStatusBar()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                //设置修改状态栏
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                //设置状态栏的颜色
                window.setStatusBarColor(getResources().getColor(R.color.white));
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }
            MIUISetStatusBarLightMode(this.getWindow(), true);
            FlymeSetStatusBarLightMode(this.getWindow(), true);
        }

        if (setTransparent()) {

        }


        mUnBinder = ButterKnife.bind(this);
        mContext = this;
        mAppComponent = Utils.getAppComponent();
        if (useLoadSir()) {
            mLoadService = LoadSir.getDefault().register(registerTarget(), new Callback.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    onPageRetry(v);
                }
            });
        }
        onViewCreated();
        loadEvent();


    }

    protected boolean setFullScreen() {
        return false;
    }

    protected boolean useDefaultStatusBar() {
        return true;
    }

    protected boolean setTransparent() {
        return false;
    }

    protected boolean setCustomTheme() {
        return false;
    }

    protected abstract void onViewCreated();

    private void loadEvent() {
        initUI();
        initData();
    }


    /**
     * 初始化控件
     */
    protected abstract void initUI();


    /**
     * 加载数据
     */
    protected abstract void initData();

    /**
     * 页面重试
     */
    protected void onPageRetry(View v) {

    }

    protected abstract int getLayoutId();

    /**
     * loadsir注册目标，默认为自身acitivity
     */
    protected Object registerTarget() {
        return this;
    }

    /**
     * 是否使用loadsir，默认不使用
     */
    protected boolean useLoadSir() {
        return false;
    }


    /**
     * 启动方法
     */
    protected void launch(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(mContext, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        mContext.startActivity(intent);
    }

    // startActivity
    public void launch(Class<?> cls) {
        launch(cls, null);
    }

    // startActivityForResult
    protected void launchForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent(mContext, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        mContext.startActivityForResult(intent, requestCode);
    }

    // startActivityForResult
    protected void launchForResult(Class<?> cls, int requestCode) {
        launchForResult(cls, null, requestCode);
    }


    @Override
    public void showLoading(String content) {
//        if (mProcessDialog == null) {
//            mProcessDialog = new ProcessDialog(this);
//        } else {
//            mProcessDialog.close();
//            mProcessDialog = new ProcessDialog(this);
//        }
//        mProcessDialog.setLoadingText(content);
//        mProcessDialog.show();
        if (hud == null) {
            hud = KProgressHUD.create(mContext)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    // .setDetailsLabel("Downloading data")
                    .setCancellable(false)
                    .setAnimationSpeed(2)
                    .setDimAmount(0.5f);
            if (!TextUtils.isEmpty(content)) {
                if (content.equals(IS_CUSTOME_SIZE)) {
                    hud.setSize(70, 70);
                } else {
                    hud.setLabel(content);
                }
            }

        } else {
            hud.dismiss();
            hud = KProgressHUD.create(mContext)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    // .setLabel("Please wait")
                    // .setDetailsLabel("Downloading data")
                    .setCancellable(false)
                    .setAnimationSpeed(2)
                    .setDimAmount(0.5f);
            if (!TextUtils.isEmpty(content)) {
                if (content.equals(IS_CUSTOME_SIZE)) {
                    hud.setSize(70, 70);
                } else {
                    hud.setLabel(content);
                }
            }
        }
        hud.show();
    }

    @Override
    public void hideLoading() {
//        if (mProcessDialog != null && mProcessDialog.isShowing()) {
//            mProcessDialog.close();
//        }
        if (hud != null && hud.isShowing()) {
            hud.dismiss();
        }
    }

    @Override
    public void showError(String message) {
        hideLoading();
        ToastUtil.showToast(message);
    }

    @Override
    public void showError(int stringId) {
        showError(getString(stringId));

    }

    @Override
    public void showMsg(String message) {
        ToastUtil.showToast(message);
    }

    @Override
    public void showMsg(int stringId) {
        showMsg(getString(stringId));
    }

    @Override
    public void showPageLoading() {
        if (mLoadService != null) {
            mLoadService.showCallback(LoadingCallback.class);
        }
    }

    @Override
    public void showPageEmpty() {
        if (mLoadService != null) {
            mLoadService.showCallback(EmptyCallback.class);
        }
    }

    @Override
    public void showPageError() {
        if (mLoadService != null) {
            mLoadService.showCallback(RetryCallback.class);
        }
    }

    @Override
    public void showPageContent() {
        if (mLoadService != null) {
            mLoadService.showSuccess();
        }
    }

    //-------------------------------------other------------------------------------------
    public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }


//    -------------------------------------生命周期---------------------------------------


    @Override
    protected void onPause() {
        super.onPause();
        if (hud != null) {
            hud.dismiss();
            hud = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnBinder != Unbinder.EMPTY) {
            mUnBinder.unbind();
        }

        this.mUnBinder = null;
        this.mAppComponent = null;
    }


}
